package com.mercator.client.graph;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

import org.vaadin.gwtgraphics.client.DrawingArea;
public class DPhenomeMap extends DGraph<GenClique, PhenomeNode, PhenomeMap> {

	public static final MapName NAME = MapName.PHENOME_MAP;
	int x_padding = 0;
	int y_padding = 100;

	public DPhenomeMap(DrawingArea canvas) {
		super(canvas);
		container = new PhenomeMap();
		factory = new PFactory();
	}

	@Override
	public void move() {
		animate();
	}
	
	@Override
	public MapName getName() {
		return NAME;
	}

	@Override
	public void moveTo(double x, double y) {
		// TODO Auto-generated method stub

	}

	public void animate() {
		System.out.println(container.getRoot());
		
		int maxdepth;
		maxdepth = Collections.min(container.getRoot()).size();
		int offset = x_padding;
		Set<PhenomeNode> others = new TreeSet<PhenomeNode>(); 
		others.addAll(container.getRoot());
		for (PhenomeNode n : container.getRoot()) 
			if(n.size() > maxdepth)
				others.remove(n);
		for (PhenomeNode n : container.getRoot()) 
			if(n.size() == maxdepth){
				offset += animate(n, maxdepth-n.size(), offset, others );
	}
}
	private int animate(PhenomeNode pn, int depth, int offset, Set<PhenomeNode> others) {
		int width = 0;
		int height = pn.getHeight() + y_padding;
		if (pn.size() == 1) {
			pn.moveTo(offset + x_padding, depth * height);
			pn.animate();
			return pn.getWidth() + x_padding;
		} else {
			depth++;
			Set<PhenomeNode> col = new HashSet<PhenomeNode>();
			for(PhenomeNode n : others)
				if (n.size() == pn.size()-1)
					col.add(n);
			others.removeAll(col);
			col.addAll(pn.adjacentNodes);
			width += animateAll(col, depth, offset, pn.size(),others);
			pn.moveTo(width / 2, (depth - 1) * height);
			pn.animate();
			return width;
		}
	}

	private int animateAll(Collection<PhenomeNode> pcol, int depth, int width,int cursize, Set<PhenomeNode> others) {
		boolean first = true;
		for (PhenomeNode pn : pcol) 
			if (cursize> pn.size()&& first){
				width += animate(pn, depth, width,others);
				first = false;
			}
			else if (cursize > pn.size())
				width += animate(pn, depth, width,Collections.<PhenomeNode> emptySet());
		return width;
	}

	@Override
	public void unselectAll() {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateSelected() {
		// TODO Auto-generated method stub

	}

	private class PFactory extends NodeFactory<GenClique, PhenomeNode> {

		@Override
		public PhenomeNode create(GenClique t) {
			PhenomeNode pn = new PhenomeNode(canvas, t);
			pn.animate();
			return pn;
		}

	}

}
